package com.zhanglijie.base.threadgroup;



/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/3/30 0030 1:21
 * 枚举线程组的子孙线程组  和所有子孙活跃线程（线程必须是活的 线程组可以是静态的）
 * enumerate（里面的递归默认是true ，列出子孙）如果给false就会只列出第一层孩子不会到孙子
 */
public class ThreadGroupEnums {
    public static void main(String[] args) {
        ThreadGroup threadGroup = new ThreadGroup("threadGroup1");
        Thread t1 = new Thread(threadGroup,()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"thread1");
        t1.start();
        Thread t2 = new Thread(threadGroup,()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"thread2");
        t2.start();

        Thread t3 = new Thread(threadGroup,()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"thread3");
        ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();

        ThreadGroup threadGroup2 = new ThreadGroup(threadGroup, "threadgroup1的孩子线程组");
        Thread t4 = new Thread(threadGroup2,()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"thread4");
        t4.start();
        ThreadGroup threadGroup3 = new ThreadGroup("main方法中创建的线程组");

        ThreadGroup[] threadGroups = new ThreadGroup[mainGroup.activeGroupCount()];
        Thread[] threads = new Thread[mainGroup.activeCount()];
        mainGroup.enumerate(threadGroups);
        mainGroup.enumerate(threads);
        for (ThreadGroup group : threadGroups) {
            System.out.println(group.getName());
        }
        System.out.println("====================");
        for (Thread t : threads) {
            System.out.println(t.getName());
        }

    }
}
